package com.carryking.smart.rpc.netty.code;

import com.carryking.smart.rpc.entity.ResponseEntity;
import com.carryking.smart.rpc.utils.KryoUtils;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * Created by jincarry on 2018/1/10.
 */
@Slf4j
public class ResponseEntityDecoder extends ByteToMessageDecoder {

    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        byte[] bytes = new byte[in.readableBytes()];
        in.readBytes(bytes);
        try {
            ResponseEntity responseEntity = KryoUtils.read(bytes, ResponseEntity.class);
            if (responseEntity != null) {
                out.add(responseEntity);
            }
            if (log.isDebugEnabled()) {
                log.debug("Decoder ResponseEntity:ResponseEntity={}", responseEntity);
            }
        } catch (Exception ex) {
            throw new RuntimeException("转换bytes为ResponseEntity时发生异常",ex);
        }
    }
}
